package cn.jdy.plugins.web;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.safe.SafeUtil;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.framework.util.ValidationUtil;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.MemberService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 会员登录控制类
 *
 * @author wuzhiliang
 * @date : 2014-03-15
 */
@Controller
@RequestMapping("/login")
public class LoginCtrl extends BaseCtrl {
	public static final String msg_00 = "00";//服务器忙，请稍后再试!
	public static final String msg_01 = "01";//请输入您的用户名或手机号或邮箱!
	public static final String msg_02 = "02";//请输入您的密码!
	public static final String msg_03 = "03";//请输入验证码!
	public static final String msg_04 = "04";//验证码错误，请重新输入!
	public static final String msg_05 = "05";//您输入的用户不存在，请重新输入!
	public static final String msg_06 = "06";//您的账号已经被锁定,24小时内禁止登录!
	public static final String msg_07 = "07";//您的帐号未被激活，请问是否现在激活!
	public static final String msg_08 = "08";//密码错误，连续输入5次错误密码帐户 需要输入验证码!
	public static final String msg_09 = "09";//您的账号已经被锁定，请联系客服解决!
	public static final String msg_10 = "10";//您输入的账户已经被禁用，请联系客服解决!
	public static final String msg_99 = "99";//登录成功!
	@Autowired
	private MemberService memberService;//会员分类业务处理类

 /**
 * 用户登录页面
 */
  @RequestMapping("")
  public ModelAndView loginIndex() {
    ModelAndView mv = new ModelAndView("/login.jsp");
    return mv;
  }
  
	/**
	 * @description 登录，先校验输入信息是否合法
	 * @author: wuzhiliang
	 * @date: 2012-10-15
	 * @return:{ "00":"服务器忙，请稍后再试!",
	 * "-1":"请输入您的用户名或手机号或邮箱!",
	 * "02":"请输入您的密码!",
	 * "03":"请输入验证码!",
	 * "04":"验证码错误，请重新输入!",
	 * "05":"您输入的用户不存在，请重新输入!",
	 * "06":"您的账号已经被锁定,24小时内禁止登录!",
	 * "07":"您的帐号未被激活，请问是否现在激活!",
	 * "08":"密码错误，连续输入5次错误密码帐户  需要输入验证码",
	 * "09":"您的账号已经被锁定，请联系客服解决!",
	 * "10":"您输入的账户已经被禁用，请联系客服解决!",
	 * "99":"登录成功!"
	 * }/web/login/forLogin?username=aaa&password=123456&code=1234&url=index.jsp
	 */
	@RequestMapping("/login")
	@ResponseBody
	public Map<String, Object> login(String loginname, String loginpwd, String code, String url,Boolean rememberMe ,HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String str = "";
		try {
			Object obj = session.getAttribute("user:" + loginname + ":passworderrorcount");
			int errorcount = 0;
			if(!StringUtil.isNullOrEmpty(obj)) {
				errorcount = (Integer) obj;
			}
	          /*校验输入信息是否合法*/
			//memberService
			str = checkUserLogin(loginname, loginpwd, code);
			if("".equals(str)) {
				Member member = memberService.findMemberByUsername(loginname);

				if(null != member) {
					if(SafeUtil.md5(loginpwd).substring(8, 16).equals(member.getPassword())) {
						if("0".equals(member.getStatus())) {
            			/*  登录成功   保存会员信息到session 并 返回*/
							String mobile = member.getMobile();
							if(!StringUtil.isNullOrEmpty(mobile)) {
								mobile = mobile.substring(0, 3) + "*****" + mobile.substring(mobile.length() - 3, mobile.length());
								member.setMobile(mobile);
							}

							session.setAttribute("user", member);
							String date;
							if(member.getLastLoginDate() != null && (date = member.getLastLoginDate().replaceAll("[^\\d]", "")).length() >= 8 && Integer.parseInt(date.substring(0, 8)) < Integer.parseInt(DateUtil.getCurrentDate(DateUtil._DEFAULT3)))
								memberService.updateMoney(member.getId(), "1".equals(member.getApprove()) ? GlobalConstant.SMONEY_LOGIN_APPROVED : GlobalConstant.SMONEY_LOGIN_UNAPPROVED);
							memberService.updateLoginDate(member.getId());
							jsonMap.put("key", "1");

							session.setAttribute("isAuthenticated", true);//标识账号密码登录
							rememberMe = rememberMe == null ? false : rememberMe;
							if(rememberMe) {
							/*  存放 Cookie */
								Cookie namecookie = new Cookie("authUser", URLEncoder.encode(loginname,"UTF-8") + "^" + member.getPassword());
								//生命周期
								namecookie.setMaxAge(60 * 60 * 24 * 15);
								//设置哪个域名写cookie
								// namecookie.setDomain("http://127.0.0.1:8080");
								namecookie.setPath("/");
								namecookie.setSecure(true);
								response.addCookie(namecookie);
							} else {
								Cookie namecookie = new Cookie("authUser", null);
								namecookie.setMaxAge(0);
								namecookie.setPath("/");
								namecookie.setSecure(true);
								response.addCookie(namecookie);
							}
						}else {
							jsonMap.put("key", "-3");
						}
					} else {
						jsonMap.put("key", "-2");
						errorcount++;
					}
				} else {
					jsonMap.put("key", "-1");
					errorcount++;
				}
				if(errorcount > 5) {
					jsonMap.put("errorcount", "8");
				}
				session.setAttribute("user:" + loginname + ":passworderrorcount", errorcount);
			} else {
				jsonMap.put("key", str);
			}
		} catch(Exception e) {
			jsonMap.put("key", "00");
			BaseLog.e(this.getClass(), "login  用户登录失败", e);
		}
		return jsonMap;
	}

	/**
	 * @description 登录表单的验证
	 * @author: wuzhiliang
	 * @date: 2014-03-15
	 */
	private String checkUserLogin(String username, String password, String code) {
		String str = "";
		try {
			if(ValidationUtil.isEmpty(username)) {
				str = msg_01;// 请输入用户名或手机号
			} else if(ValidationUtil.isEmpty(password)) {
				str = msg_02;// 请输入密码
			}
			if(!StringUtil.isNullOrEmpty(request.getSession().getAttribute("verifyWord"))) {
				if("".equals(code)) {
					str = msg_03;// 请输入验证码
				} else if(!code.equals(request.getSession().getAttribute("verifyWord"))) {
					str = msg_04;// 验证码错误
				}
			}
		} catch(Exception e) {
			str = msg_00;//服务器忙,请稍后再试!
			BaseLog.e(this.getClass(), "checkUserLogin登陆表单输入合法性校验异常", e);
		}
		return str;
	}

	/**
	 * 用户退出登录
	 */
	@RequestMapping("/quit")
	public ModelAndView quit() {
		ModelAndView mv = new ModelAndView("/login.jsp?errorType=9");
		session.removeAttribute("user");
		session.invalidate();
		return mv;
	}
	
	/**
   * 登录界面找回密码
   * 会员管理用手机号重置密码
   *
   * @return
   */
  @RequestMapping("/forUpdatePwdLogin")
  public ModelAndView forUpdatePwdLogin(String password,String mobile,String authcode1) {
    ModelAndView mv = new ModelAndView("redirect:/login?errorType=10");
    try {
      if(!(authcode1==null || "".equals(authcode1.trim()))){
        String phonecode = (String)session.getAttribute(GlobalConstant._PHONECODE);
        
         if(phonecode!=null && authcode1.equals(phonecode)){
           memberService.updatepwd(mobile, SafeUtil.md5(password).substring(8, 16));
           session.invalidate();
         }else{
           mv = new ModelAndView("redirect:/login?errorType=11");
         }
      }else{
        mv = new ModelAndView("redirect:/login?errorType=11");
      }
    } catch(BaseException e) {
      BaseLog.e(this.getClass(), "updResetPwd:密码修改有误", e);
    }
    return mv;
  }
}